<?php

if (!defined('BASEPATH'))
    exit('No direct script access allowed');

class Producto extends CI_Controller {
    
    public $ruta_template;
    public $fields_table;
    public $fields_form;
    public $fields_detalles;
    public $validate_fields;

    function __construct(){
        parent::__construct();
        if($this->session->userdata('idusuario') == null){show_404();}
        $this->lang->load('lang/pro_'.$this->config->item('language'), $this->config->item('language'));
        $this->load->model('producto_model');
        $this->load->library('form_validation');
        $this->ruta_template = array('ruta' => site_url().'public/'.$this->template->getActiveTemplate(),
                                     'ruta_archivos' => 'templates/traveltemplate/');
        $this->template->write_view('footer', 'footer');
        $this->template->write_view('header', 'header');
        $this->template->write_view('_scripts', 'js', $this->ruta_template);
        $this->template->write_view('_styles', 'css', $this->ruta_template);
        $this->fields_table = array('', 'pro_idproducto', 'pro_descripcion', 'pti_descripcion');
        
        $this->fields_form = array('pro_idproducto', 'pro_descripcion', 'pro_idtipo');
        $this->validate_fields = array('', 'trim|required', 'trim|required');

        $this->fields_detalles = array('pro_direccion', 'pro_numero', 'pro_piso', 'pro_antiguedad', 'pro_ultima_reforma', 'pro_provincia', 'pro_municipio', 'pro_web',
                'pro_codigopostal', 'pro_barrio', 'pro_pi_fianza', 'pro_impfianza', 'pro_pi_reserva', 'pro_impreserva', 'pro_limpieza', 'pro_entorno');
        $this->validate_detalles = array('trim|required', 'trim|required', 'trim|required', 'trim|required', '', '', 'trim|required');
        
        $this->fields_distacia = array('dst_iddistancia', 'dst_descripcion');    
    }

    public function getTemplate(){
        $row = '<tr value="%TABLEID%" bgcolor="white">';
        return array ('table_open'  => '<table id="tabla">', 'row_start'  => $row, 'row_alt_start'  => $row);
    }

    public function index(){
        $this->load->library('table');
        $this->table->set_heading(array_slice($this->fields_table, 1));
        $this->table->set_template($this->getTemplate());
        $data['tabla'] = $this->table->generate($this->producto_model->getProductos(array_slice($this->fields_table, 1)), strtolower(__CLASS__), true, $this->session->userdata('empresa'));
        $this->template->write_view('content', 'content/producto', $data);
        $this->template->render();
    }

    public function borrar($codigo = ''){
        $this->producto_model->borrar($codigo);
        redirect('producto');
    }
    
    public function agregar(){
        $this->load->library('table');
        $this->load->library('form_creator');

        $this->form_creator->setTabla(strtolower(__CLASS__));
        $hidden  = $this->form_creator->pintaCampo(array('field' => "p_accion", 'type' => 'HDN', 'value' => 'C'));
        $campos = array();
        for($x = 1; $x < count($this->fields_form); $x++){
            $campos[] = lang($this->fields_form[$x]);
            $campos[] = $this->switch_comun($this->fields_form[$x]);
        }

        $new_list = $this->table->make_columns($campos, 4);
        $data['tabla'] = $hidden.$this->table->generate($new_list, strtolower(__CLASS__));
        $data['ce'] = "A";
        $this->template->write_view('content', 'content/producto_ce', $data);
        $this->template->render();
    }

    public function editar($indice = ''){
        $this->load->library('table');
        $this->load->library('form_creator');

        $producto = $this->producto_model->getProductos($this->fields_form, $indice, $this->session->userdata('empresa'));
        $this->form_creator->setTabla(strtolower(__CLASS__));
        $row = $producto->row_array();
        $idproducto = $row[$this->fields_form[0]];
        $hidden  = $this->form_creator->pintaCampo(array('field' => $this->fields_form[0], 'type' => 'HDN', 'value' => $row[$this->fields_form[0]]));
        $hidden .= $this->form_creator->pintaCampo(array('field' => "p_accion", 'type' => 'HDN', 'value' => 'E'));
        $hidden .= $this->form_creator->pintaCampo(array('field' => "p_campos", 'type' => 'HDN', 'value' => $indice));
        $campos = array();
        for($x = 1; $x < count($this->fields_form); $x++){
            $campos[] = lang($this->fields_form[$x]);
            $campos[] = $this->switch_comun($this->fields_form[$x], $row[$this->fields_form[$x]]);
        }
        $new_list = $this->table->make_columns($campos, 4);
        $data['tabla'] = $hidden.$this->table->generate($new_list, strtolower(__CLASS__));
        $data['ce'] = "E";
        /**********Detalles***********/
        $producto = $this->producto_model->getProductos($this->fields_detalles, $indice, $this->session->userdata('empresa'));
        $row = $producto->row_array();  
        $campos = array();
        for($x = 0; $x < count($this->fields_detalles); $x++){
            $campos[] = "<span id='tit_".$this->fields_detalles[$x]."'>".lang($this->fields_detalles[$x])."</span>";
            $campos[] = $this->switch_comun($this->fields_detalles[$x], $row[$this->fields_detalles[$x]]);
        }
        $new_list = $this->table->make_columns($campos, 4);
        $data['detalles'] = $hidden.$this->table->generate($new_list, strtolower(__CLASS__));
        /**********fin Detalles***********/

        /**********Distancias***********/
        $campos = array();
        $producto = $this->producto_model->getDistancia();
        foreach ($producto->result_array() as $distancia){
            $campos[] = lang($distancia['desc']);
            $valor_distancia = $this->producto_model->getValorDistancia($idproducto, $distancia['id']);
            $row = $valor_distancia->row_array();
            $campos[] = $this->form_creator->pintaCampo(array('field' => 'distancia_'.$distancia['id'], 
                                                            'value' => ($row != null ? $row['desc'] : '')));
        }
        $new_list = $this->table->make_columns($campos, 4);
        $data['distancias'] = $hidden.$this->table->generate($new_list, strtolower(__CLASS__));
        /**********fin Distancias***********/
        
        /**********Distribucion***********/
        $campos = array();
        $producto = $this->producto_model->getDistribucion();
        foreach ($producto->result_array() as $distribucion){
            $campos[] = lang($distribucion['desc']);
            $valor_distribucion = $this->producto_model->getValorDistribucion($idproducto, $distribucion['id']);
            $row = $valor_distribucion->row_array();
            $campos[] = $this->form_creator->pintaCampo(array('field' => 'distribucion_'.$distribucion['id'], 
                                                            'value' => ($row != null ? $row['desc'] : '')));
        }
        $new_list = $this->table->make_columns($campos, 4);
        $data['distribuciones'] = $hidden.$this->table->generate($new_list, strtolower(__CLASS__));
        /**********fin Distribucion***********/
        /**********Fotos***********/
        $campos = array();
        $campos[] = lang('anyadir_foto').": ";
        $campos[] = $this->form_creator->pintaCampo(array('field' => 'p_upload', 'value' => '', 'type' => 'FIL', 'style' => 'size="50"'));
        $campos[] = "&nbsp;";
        $campos[] = lang('descripcion_foto').": ";
        $campos[] = $this->form_creator->pintaCampo(array('field' => 'p_descripcion', 'value' => '', 'style' => 'size="70"'));
        $campos[] = "&nbsp;";
        $new_list = $this->table->make_columns($campos, 3);
        $data['form_fotos'] = $hidden.$this->table->generate($new_list, strtolower(__CLASS__));
        
        $campos = array();
        $campos[] = "<u><b>".lang('fotos_cargadas').": </b></u>";
        $campos[] = "&nbsp;";
        $campos[] = "&nbsp;";
        $producto = $this->producto_model->getFoto($idproducto);    
        foreach ($producto->result_array() as $foto){
            if(file_exists("./".$foto['url'])){
                if(is_file("./".$foto['url'])){
                    $cad_imagen  = '<ul class="gallery-list clearfix">';
                    $cad_imagen .= '<li class="box">';
                    if($foto['default'] == 'S'){
                        $cad_imagen .= '<div class="entry-header" style="border: 3px solid #b70e4f;">';
                    }else{
                        $cad_imagen .= '<div class="entry-header">';
                    }
                    $cad_imagen .= '<div class="zoom">';
                    $cad_imagen .= '<a class="multi_images" href="'.site_url().$foto['url'].'">';
                    $cad_imagen .= '<img class="gallery-image" src="'.site_url().$foto['url_thumb'].'" style="opacity: 1;" width="230">';
                    $cad_imagen .= '</a>';
                    $cad_imagen .= '</div>';
                    $cad_imagen .= '<h6>'.$foto['desc'].'</h6>';
                    if($foto['default'] != 'S'){
                        $cad_imagen .= '<form action="'.site_url('producto/marcar_predeterminada').'" method="post">';
                        $cad_imagen .= '<input type="hidden" name="p_url" id="p_url" value="'.site_url().$this->uri->uri_string().'"/>';
                        $cad_imagen .= '<input type="hidden" name="p_idfoto" id="p_idfoto" value="'.$foto['id'].'"/>';
                        $cad_imagen .= '<input type="hidden" name="p_idproducto" id="p_idproducto" value="'.$idproducto.'"/>';
                        $cad_imagen .= '<div class="botonContenedor"><input type="submit" class="boton flecha" value="'.lang('marcar_foto_principal').'"/></div>';
                        $cad_imagen .= '</form>';
                    }

                    $cad_imagen .= '<form action="'.site_url('producto/eliminar_foto').'" method="post">';
                    $cad_imagen .= '<input type="hidden" name="p_url" id="p_url" value="'.site_url().$this->uri->uri_string().'"/>';
                    $cad_imagen .= '<input type="hidden" name="p_idfoto" id="p_idfoto" value="'.$foto['id'].'"/>';
                    $cad_imagen .= '<input type="hidden" name="p_idproducto" id="p_idproducto" value="'.$idproducto.'"/>';
                    $cad_imagen .= '<div class="botonContenedor"><input type="submit" class="boton rollback" value="Eliminar foto"/></div>';                    
                    $cad_imagen .= '</form>';
                    $cad_imagen .= '</div>';
                    $cad_imagen .= '</li>';
                    $cad_imagen .= '</ul>';

                    $campos[] = $cad_imagen;
                }
            }
        }
        $new_list = $this->table->make_columns($campos, 3);
        $data['fotos'] = $hidden.$this->table->generate($new_list, strtolower(__CLASS__));
        /**********fin Fotos***********/
        /**********Tarifas************/
        $campos = array();
        $campos[] = "<b>".lang('insercion_modificacion_tarifa_dispo').": "."</b>";
        $new_list = $this->table->make_columns($campos, 1);
        $data['tarifas'] = $this->table->generate($new_list, strtolower(__CLASS__));
        $campos = array();
        $hidden .= $this->form_creator->pintaCampo(array('field' => "p_operacion_tarifa", 'type' => 'HDN', 'value' => ''));
        $hidden .= '<input type="hidden" name="p_url" id="p_url" value="'.site_url().$this->uri->uri_string().'"/>';
        $hidden .= '<input type="hidden" name="p_idreserva" id="p_idreserva"/>';
        $cadenaform = '<form name="form" action="'.site_url('producto/tarifas').'" method="post">';
        $cadenaformfin = '</form>';
        $campos[] = lang('fecha_desde').": ";
        $campos[] = $this->form_creator->pintaCampo(array('field' => 'datefrom', 'value' => '', 'style' => 'size="10"'));
        $campos[] = lang('fecha_hasta').": ";
        $campos[] = $this->form_creator->pintaCampo(array('field' => 'dateto', 'value' => '', 'style' => 'size="10"'));
        $campos[] = lang('importe_total').": ";
        $campos[] = $this->form_creator->pintaCampo(array('field' => 'p_importe', 'value' => ''));
        $campos[] = '<div class="botonContenedor"><input type="submit" onclick="document.getElementById(\'p_operacion_tarifa\').value=\'T\'" class="boton modify" value="'.lang('cambiar_tarifa').'" style="padding-bottom: 0px;"/></div>';
        $campos[] = '<div class="botonContenedor"><input type="submit" onclick="document.getElementById(\'p_operacion_tarifa\').value=\'V\'" class="boton delete" value="'.lang('cerrar_ventas').'" style="padding-bottom: 0px;"/></div>';
        $campos[] = '<div class="botonContenedor"><input type="submit" onclick="document.getElementById(\'p_operacion_tarifa\').value=\'C\'" class="boton sobre" value="'.lang('pedir_confirmacion').'" style="padding-bottom: 0px;"/></div>';
        $this->table->set_template(array('table_open' => '<table border="0" width="100%" cellpadding="0" cellspacing="0">'));
        $new_list = $this->table->make_columns($campos, 9);
        $data['tarifas'] .= $cadenaform.$hidden.$this->table->generate($new_list, strtolower(__CLASS__)).$cadenaformfin;
        
        $this->lang->load('lang/cal_'.$this->config->item('language'), $this->config->item('language'));
        $data_tarifas['info_reservas'] = $this->producto_model->getReservasJson($idproducto);
        $data_tarifas['info_tarifas'] = $this->producto_model->getTarifasJson($idproducto);
        $data_tarifas['producto'] = $idproducto;
        $data_tarifas['ruta'] = $this->ruta_template['ruta'];
        //$variables['includes'] = $this->load->view($this->ruta_template['ruta_archivos'].'js_css_calendar', $data_tarifas, true);
        $data['tarifas'] .= $this->load->view($this->ruta_template['ruta_archivos'].'content/producto_ce_calendar', $data_tarifas, true);
        /**********fin Tarifas************/
        /**********Contenidos***********/
        $campos = array();
        $producto = $this->producto_model->getContenido();
        $tipo_contenido_pasado = "";
        foreach ($producto->result_array() as $contenido){
            if($contenido['tipo'] != $tipo_contenido_pasado){
                $tipo_contenido = $this->producto_model->getDescTipoContenido($contenido['tipo']);
                if(count($campos) % 4 > 0){
                    $campos[] = "";
                    $campos[] = "";
                }
                if(count($campos) > 4){
                    $campos[] = "";
                    $campos[] = "";
                    $campos[] = "";
                    $campos[] = "";
                }
                $campos[] = "<u><b>".lang($tipo_contenido)."</b></u>";
                $campos[] = "";
                $campos[] = "";
                $campos[] = "";
            }
            $campos[] = lang($contenido['desc']);
            $valor_contenido = $this->producto_model->getValorContenido($idproducto, $contenido['id']);
            $row = $valor_contenido->row_array();
            $campos[] = $this->form_creator->pintaCampo(array('field' => 'contenido_'.$contenido['id'], 'type' => 'CHK',
                                                            'value' => ($row != null ? $row['desc'] : '')));
            $tipo_contenido_pasado = $contenido['tipo'];
        }
        $new_list = $this->table->make_columns($campos, 4);
        $data['contenidos'] = $hidden.$this->table->generate($new_list, strtolower(__CLASS__));
        /**********fin Contenidos***********/        
        $this->template->write_view('content', 'content/producto_ce', $data);
        $this->template->render();
    }
    
    public function onChangeMesCalendarioTarifa(){
        echo json_encode($this->producto_model->getTarifasJson($this->input->post('producto'), $this->input->post('mes')));
    }

    public function onChangeMesCalendarioReserva(){
        echo json_encode($this->producto_model->getReservasJson($this->input->post('producto'), $this->input->post('mes')));
    }
    
    public function tarifas(){
        $this->load->library('General');
        $num_dias = $this->general->restar_fechas($this->input->post('datefrom'), $this->input->post('dateto'));
        if($_POST['p_operacion_tarifa'][0] == 'V'){
            $resultado = $this->producto_model->agregar_cierres($_POST['pro_idproducto'][0],
                                                                $this->general->fec_str_to_ymd($this->input->post('datefrom')),
                                                                $this->general->fec_str_to_ymd($this->input->post('dateto')));
            if(!$resultado){
                $this->session->set_flashdata('message_cierre', lang('existe_reserva_dias_cierre'));            
            }
        }else{
            for($x = 0; $x <= $num_dias; $x++){
                $dia = $this->general->sumar_dias($this->input->post('datefrom'), $x);
                log_message('error', 'dia: '.$dia);
                switch ($_POST['p_operacion_tarifa'][0]) {
                    case 'T':
                        $this->producto_model->agregar_tarifas($_POST['pro_idproducto'][0], 
                                                            $this->general->fec_str_to_mysql($dia), 
                                                            $this->input->post('p_importe'));
                        break;
                    case 'C':
                        $this->producto_model->agregar_confirmaciones($_POST['pro_idproducto'][0], 
                                                                    $this->general->fec_str_to_mysql($dia));
                        break;
                }        
            }
        }
        redirect($_POST['p_url'], 'refresh');
    }
    
    public function eliminar_cierre($idcierre, $url){
        $this->producto_model->eliminar_cierres($idcierre);
        redirect(str_replace("_", "/", $url), 'refresh');
    }

    public function marcar_predeterminada(){
        $this->producto_model->marcarFoto();
        redirect($_POST['p_url'], 'refresh');
    }
    
    public function eliminar_foto(){
        $foto_eliminada = $this->producto_model->eliminar_foto();
        $foto_eliminada_thumb = substr($foto_eliminada, 0, strpos($foto_eliminada, '.'))."_thumb.".substr(strrchr($foto_eliminada, '.'), 1);
        unlink('./'.$this->config->item('ruta_uploads').$this->session->userdata('empresa')."/".$foto_eliminada);
        unlink('./'.$this->config->item('ruta_uploads').$this->session->userdata('empresa')."/thumb/".$foto_eliminada_thumb);
        unlink('./'.$this->config->item('ruta_uploads').$this->session->userdata('empresa')."/thumb_mini/".$foto_eliminada_thumb);
        redirect($_POST['p_url'], 'refresh'); 
    }
    
    public function guardar_fotos(){
        $this->session->set_userdata(array('tab_sel' => 'fotos'));
        $fecha = new DateTime();
        $filename = $fecha->getTimestamp();
        $extension = substr(strrchr($_FILES['p_upload']['name'], '.'), 1);
        $completo = $filename.".".$extension;
        $completo_thumb = $filename."_thumb.".$extension;
        $config['upload_path'] = $this->config->item('ruta_uploads').$this->session->userdata('empresa')."/";
        $config['allowed_types'] = 'gif|jpg|jpeg|png';
        $config['max_size'] = '1000';
        $config['max_width'] = '1024';
        $config['max_height'] = '768';
        $config['file_name'] = $filename;

        $this->load->library('upload', $config);
        
        if(!is_dir($config['upload_path'])){
            mkdir($config['upload_path'], 0777, true);
        }
        
        if (!$this->upload->do_upload('p_upload')){
            redirect($_POST['p_url'], 'refresh');
        }else{
            $this->load->library('image_lib');
            $this->crear_thumb($config['upload_path'], '300', '300', $completo);
            $this->crear_thumb_mini($config['upload_path'], '60', '60', $completo);
            /*Resize de la imagen clave*/
            $conf['source_image'] = $config['upload_path'].$completo; // ruta donde se encuentra la imagen
            $conf['source_folder'] = $config['upload_path'];
            $conf['width'] = '640';
            $conf['height'] = '640';
            $conf['maintain_ratio'] = TRUE;
            $conf['dynamic_output'] = false;
            $conf['quality'] = '75%';    // calidad de la imagen
            $conf['create_thumb'] = false;
            $this->image_lib->initialize($conf);
            $this->image_lib->resize();
            $this->image_lib->clear();
            /*Fin resize de la imagen clave*/
            $this->producto_model->insertar_fotos($_POST['p_descripcion'], $config['upload_path'].$completo, 
                    $config['upload_path']."thumb/".$completo_thumb, $config['upload_path']."thumb_mini/".$completo_thumb);
            redirect($_POST['p_url'], 'refresh');
        }
    }
    
    public function crear_thumb($ruta = '', $width = '', $height = '', $nombre_completo = ''){
        if (!file_exists($ruta."thumb/")) mkdir($ruta."thumb/", 0777, true);
        $conf['source_image'] = $ruta.$nombre_completo; // ruta donde se encuentra la imagen
        $conf['source_folder'] = $ruta;
        $conf['new_image'] = $ruta."thumb/".$nombre_completo; // ruta donde se encuentra la imagen

        $conf['width'] = $width;
        $conf['maintain_ratio'] = TRUE;
        $conf['height'] = $height;
        $conf['dynamic_output'] = false;
        $conf['create_thumb'] = TRUE;
        $conf['quality'] = '75%';    // calidad de la imagen

        $this->image_lib->initialize($conf);
        $this->image_lib->resize();
        $this->image_lib->clear();    
    }
    
    public function crear_thumb_mini($ruta = '', $width = '', $height = '', $nombre_completo = ''){
        if (!file_exists($ruta."thumb_mini/")) mkdir($ruta."thumb_mini/", 0777, true);
        $conf['source_image'] = $ruta.$nombre_completo; // ruta donde se encuentra la imagen
        $conf['source_folder'] = $ruta;
        $conf['new_image'] = $ruta."thumb_mini/".$nombre_completo; // ruta donde se encuentra la imagen

        $conf['width'] = $width;
        $conf['height'] = $height;
        $conf['maintain_ratio'] = TRUE;
        $conf['dynamic_output'] = false;
        $conf['create_thumb'] = TRUE;
        $conf['quality'] = '75%';    // calidad de la imagen

        $this->image_lib->initialize($conf);
        $this->image_lib->resize();
        $this->image_lib->clear();    
    }    
    
    public function guardar_distancias(){
        $this->session->set_userdata(array('tab_sel' => 'distancias'));
        foreach ($this->input->post() as $key => $value) {
            if(strpos($key, "distancia") !== false){
                $this->producto_model->insertar_distancias(substr($key, strrpos($key, "_")+1), $_POST['pro_idproducto'][0], $value);
            }
        }
        redirect($_POST['p_url'], 'refresh');
    }
    
    public function guardar_contenidos(){
        $this->session->set_userdata(array('tab_sel' => 'contenidos'));
        $this->producto_model->eliminar_contenidos($_POST['pro_idproducto'][0]);
        foreach ($this->input->post() as $key => $value) {
            if(strpos($key, "contenido") !== false){
                $this->producto_model->insertar_contenidos(substr($key, strrpos($key, "_")+1), $_POST['pro_idproducto'][0], ($value == 'on' ? 'S' : 'N'));
            }
        }
        redirect($_POST['p_url'], 'refresh');
    }
    
    public function guardar_distribuciones(){
        $this->session->set_userdata(array('tab_sel' => 'distribucion'));
        foreach ($this->input->post() as $key => $value) {
            if(strpos($key, "distribucion") !== false){
                $this->producto_model->insertar_distribuciones(substr($key, strrpos($key, "_")+1), $_POST['pro_idproducto'][0], $value);
            }
        }
        redirect($_POST['p_url'], 'refresh');
    }

    public function guardar($pantalla = ''){
        $this->session->set_userdata(array('tab_sel' => 'detalles'));
        $accion = $_POST['p_accion'][0];
        $parametros = array();

        switch ($pantalla) {
            case '1':
                for($z = 0; $z < count($this->validate_detalles); $z++){
                    $this->form_validation->set_rules($this->fields_detalles[$z].'[]', 'lang:'.$this->fields_detalles[$z], $this->validate_detalles[$z]);
                }
                break;        
            default:
                for($z = 1; $z < count($this->validate_fields); $z++){
                    $this->form_validation->set_rules($this->fields_form[$z].'[]', 'lang:'.$this->fields_form[$z], $this->validate_fields[$z]);
                }
                break;
        }
        if($this->form_validation->run() == FALSE){
            if($accion == 'C'){
                redirect('producto/agregar');
            }else if($accion == 'E'){
                $this->editar($_POST['p_campos'][0]);
                return;
            }
	}
        foreach ($this->input->post() as $key => $value) {
            for($i = 0; $i < count($value); $i++){
                if(strpos($key, "pro") !== false){
                    if($value[$i] != ''){
                        $parametros[$i][$key] = $value[$i];
                    }
                }
            }
        }
        if($accion == 'C'){
            $parametros[0]['pro_empresa'] = $this->session->userdata('empresa');
            $parametros[0]['pro_idusuario'] = $this->session->userdata('idusuario');
            $insert_id = $this->producto_model->guardar($parametros[0]);
            $this->session->set_flashdata('message', lang('successfully_created'));
            //fEnviaMailCreaUsuario('pepmahou@hotmail.com', 'Prueba', 'Texto de prueba');
            redirect('producto/editar/'.$insert_id, 'refresh');
        }else if($accion == 'E'){
            $parametros[0]['pro_empresa'] = $this->session->userdata('empresa');
            $parametros[0]['pro_idusuario'] = $this->session->userdata('idusuario');
            $this->producto_model->actualizar($parametros[0]);
            redirect('producto/editar/'.$_POST['p_campos'][0], 'refresh');
        }
    }

    function switch_comun($field = '', $value = ''){
        $this->load->helper('settings');
        switch ($field) {
            case 'pro_idtipo':
                return $this->form_creator->pintaCampo(array('field' => $field,
                                                             'type' => 'SEL',
                                                             'code' => generaOptionsCombo($this->producto_model->getTipos(), $value)
                                                       ));
                break;
            case 'pro_entorno':
                return $this->form_creator->pintaCampo(array('field' => $field,
                                                             'type' => 'SEL',
                                                             'code' => generaOptionsCombo($this->producto_model->getEntorno(), $value)
                                                       ));
                break;
            case 'pro_provincia':
                return $this->form_creator->pintaCampo(array('field' => $field,
                                                             'type' => 'SEL',
                                                             'code' => generaOptionsCombo($this->producto_model->getProvincia(), $value)
                                                       ));
                break;
            case 'pro_municipio':
                return $this->form_creator->pintaCampo(array('field' => $field,
                                                             'type' => 'SEL',
                                                             'code' => generaOptionsCombo($this->producto_model->getMunicipio('', $value), $value),
                                                             'style' => 'style="width: 250px"'
                                                       ));
                break;
            case 'pro_pi_fianza':
            case 'pro_pi_reserva':
                return $this->form_creator->pintaCampo(array('field' => $field,
                                                             'type' => 'RAD',
                                                             'value' => $value,
                                                             'num_radio' => 2,
                                                             'descriptions' => array(lang('porcentaje'), lang('importe'))
                                                       ));
                break;
            default:
                return $this->form_creator->pintaCampo(array('field' => $field, 'value' => $value));
        }        
        return $this->form_creator->pintaCampo(array('field' => $field, 'value' => $value));
    }
    
    function getMunicipios(){
        $this->load->helper('settings');
        echo generaOptionsCombo($this->producto_model->getMunicipio($this->input->post('provincia')));
    }
}

?>